import { login, getUserInfo } from '@/api/user'

const state = {
  token: localStorage.getItem('token'),
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    // 保存到 localStorage
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
  CLEAR_USER: (state) => {
    state.token = null
    state.userInfo = null
    // 清除 localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('usId')
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { usAccount, usPassword } = userInfo
    return new Promise((resolve, reject) => {
      login({ usAccount, usPassword }).then(response => {
        const { token, data } = response
        localStorage.setItem('token', token)
        localStorage.setItem('usId', data?.usId)
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', data)
        resolve(true)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        if (!response) {
          reject(new Error('获取用户信息失败，请重新登录'))
          return
        }
        commit('SET_USER_INFO', response?.data)
        resolve(response?.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 登出
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('CLEAR_USER')
      // 清除动态路由
      commit('permission/SET_ROUTES', [], { root: true })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 